/**

 * @File SummaryAccountTemplateDaoImpl.java
 * @author Agam Bhamra
 * @Version 1.0
 * @Date July 27, 2013
 * 
 * Copyright (c) 2011 EdRP, Dayalbagh Educational Institute.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this  list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL ETRG OR ITS CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributors: Members of EdRP, Dayalbagh Educational Institute
 */

package in.ac.dei.edrp.generalLedger.summaryAccount;


import flex.messaging.FlexContext
;
import flex.messaging.FlexSession;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.stereotype.Component;

import com.ibatis.sqlmap.client.SqlMapClient;

@Component
@Qualifier("SummaryAccountTemplateDaoImpl")
public class SummaryAccountTemplateDaoImpl extends SqlMapClientDaoSupport implements SummaryAccountTemplateDao {
	
	private static Logger logObj = Logger.getLogger(SummaryAccountTemplateDaoImpl.class);
	
	public SummaryAccountTemplateDaoImpl() {}
	@Autowired
	
	public SummaryAccountTemplateDaoImpl(SqlMapClient sqlMapClient)
	{
		setSqlMapClient(sqlMapClient);
	}
	
	public List<SummaryAccountTemplateInfoBean> getLedgers()
	{
		List<SummaryAccountTemplateInfoBean> ledgers = null;
		try {
			ledgers = getSqlMapClientTemplate().queryForList("summaryAccountTemplate.getLedgers");
		} catch (Exception e) {
			logObj.info("Exception in getting Ledgers  - getLedgers method");
			logObj.error(e);
			System.out.println("Error in getLedgers:                 \nStart\n"+e+"\nend\n");
		}
		return ledgers;
	}
	
	
	public String addSummaryAccountTemplate (final List<Map<String, String>> obj,final SummaryAccountTemplateInfoBean input) {
		String status="";
		try{
			if(obj.size()>0)
			{
				for(int i=0;i<obj.size();i++)
				{
					System.out.println("addSummaryAccountTemplate Started");
					FlexSession session = FlexContext.getFlexSession();
			 		input.setUserId(session.getAttribute("userId").toString());
					input.setTemplateName(obj.get(i).get("templateName"));
					input.setLegalEntityIdentifier(obj.get(i).get("ledgerEntityIdentifier"));
					input.setSegmentId(obj.get(i).get("segmentId"));
					input.setTemplate(obj.get(i).get("template"));
					input.setDescription(obj.get(i).get("description"));
					input.setEarliestPeriod(obj.get(i).get("earliestPeriod"));
					input.setStatus(obj.get(i).get("status"));	
					input.setFlexFieldId(obj.get(i).get("flexFieldId"));
					
					SummaryAccountTemplateInfoBean templateId =new SummaryAccountTemplateInfoBean();
					templateId = (SummaryAccountTemplateInfoBean) getSqlMapClientTemplate().queryForObject("summaryAccountTemplate.addSummaryAccountTemplateProcedure",input);
					String str = templateId.getTemplateId();
					input.setTemplate(obj.get(i).get("templateValueId"));
					
					int counter=0;
					while(input.getTemplate().indexOf(".")>=0 && input.getSegmentId().indexOf(".")>=0)
					{counter++;
						SummaryAccountTemplateInfoBean templateDetails = new SummaryAccountTemplateInfoBean();
						templateDetails.setTemplate(input.getTemplate().substring(0, input.getTemplate().indexOf(".")));
						templateDetails.setSegmentId(input.getSegmentId().substring(0, input.getSegmentId().indexOf(".")));
						templateDetails.setFlexFieldId(input.getFlexFieldId());
						templateDetails.setUserId(input.getUserId());
						templateDetails.setTemplateId(str);
//						templateDetails.setSegmentId(segmentId);
//						System.out.println(counter+":	"+input.getSegmentId().substring(0, input.getSegmentId().indexOf("."))+"	"+input.getTemplate().substring(0, input.getTemplate().indexOf(".")));
//						System.out.println("in query details: \nFlex Field Id: "+templateDetails.getFlexFieldId()
//								+"\nTemplate Id: "+templateDetails.getFlexFieldId()+
//								"\nSegment Id: "+templateDetails.getTemplateId()+
//								"\nTemplate: "+ templateDetails.getTemplate());
						getSqlMapClientTemplate().insert("summaryAccountTemplate.addSummaryAccountTemplateDetails", templateDetails);
						input.setTemplate(input.getTemplate().substring(input.getTemplate().indexOf(".")+1, input.getTemplate().length()));
						input.setSegmentId(input.getSegmentId().substring(input.getSegmentId().indexOf(".")+1, input.getSegmentId().length()));
						
					}
					if(input.getTemplate().indexOf(".")<0 && input.getSegmentId().indexOf(".")<0)
					{
						System.out.println(counter+1+":	"+input.getSegmentId()+"	"+input.getTemplate());
						SummaryAccountTemplateInfoBean templateDetails = new SummaryAccountTemplateInfoBean();
						templateDetails.setTemplate(input.getTemplate());
						templateDetails.setSegmentId(input.getSegmentId());
						templateDetails.setFlexFieldId(input.getFlexFieldId());
						templateDetails.setUserId(input.getUserId());
						templateDetails.setTemplateId(str);
						getSqlMapClientTemplate().insert("summaryAccountTemplate.addSummaryAccountTemplateDetails", templateDetails);
					}
					else
						System.out.println("error");
					
					status="done";
					System.out.println("addSummaryAccountTemplate Completed");
				}
			}
		}
		catch (Exception e)
		{
			logObj.info("Exception in getting SummaryAccountTemplate  - addSummaryAccountTemplate method");
			logObj.error(e);
			System.out.println("Error in addSummaryAccountTemplate:                 \nStart\n"+e+"\nend\n");
			status=e.getClass().toString();
		}
		return status;
		
	}
	
	public List<SummaryAccountTemplateInfoBean> getSummaryAccountTemplates()
	{
		List<SummaryAccountTemplateInfoBean> summaryAccountTemplates = null;
		try {
			summaryAccountTemplates = getSqlMapClientTemplate().queryForList("summaryAccountTemplate.getSummaryAccountTemplates");
		} catch (Exception e) {
			logObj.info("Exception in getting Summary Account Templates  - getSummaryAccountTemplates method");
			logObj.error(e);
			System.out.println("Error in getSummaryAccountTemplates:                 \nStart\n"+e+"\nend\n");
		}
		return summaryAccountTemplates;
	}
	
	public String deleteSummaryAccountTemplate (String id) {
		String status="";
		try{
				getSqlMapClientTemplate().delete("summaryAccountTemplate.deleteSummaryAccountTemplate", id);
				getSqlMapClientTemplate().delete("summaryAccountTemplate.deleteSummaryAccountTemplateDetails", id);
				status = "done";
		}
		catch (Exception e)
		{
			logObj.info("Exception in  deleting Summary Account Template  - deleteSummaryAccountTemplate method");
			logObj.error(e);
			System.out.println("Error in deleteSummaryAccountTemplate:                 \nStart\n"+e+"\nend\n");
			status=e.getClass().toString();
		}
		return status;
		
	}
	

	public List<SummaryAccountTemplateInfoBean> getSegments()
	{
		List<SummaryAccountTemplateInfoBean> segments = null;
		try {
			segments = getSqlMapClientTemplate().queryForList("summaryAccountTemplate.getSegments");
		} catch (Exception e) {
			logObj.info("Exception in getting segments  - getSegments method");
			logObj.error(e);
			System.out.println("Error in getSegments:                 \nStart\n"+e+"\nend\n");
		}
		return segments;
	}
	
	public String editSummaryAccountTemplate (final List<Map<String, String>> obj,final SummaryAccountTemplateInfoBean input) {
		String status="";
		try{
			if(obj.size()>0)
			{
				for(int i=0;i<obj.size();i++)
				{
					System.out.println("editSummaryAccountTemplate Started");
					FlexSession session = FlexContext.getFlexSession();
			 		input.setUserId(session.getAttribute("userId").toString());
					input.setTemplateName(obj.get(i).get("templateName"));
					input.setLegalEntityIdentifier(obj.get(i).get("ledgerEntityIdentifier"));
					input.setTemplateId(obj.get(i).get("templateId"));
					input.setSegmentId(obj.get(i).get("segmentId"));
					input.setTemplate(obj.get(i).get("template"));
					input.setDescription(obj.get(i).get("description"));
					input.setEarliestPeriod(obj.get(i).get("earliestPeriod"));
					input.setStatus(obj.get(i).get("status"));	
					input.setFlexFieldId(obj.get(i).get("flexFieldId"));
					input.setTemplateEdited(obj.get(i).get("templateEdited"));
					getSqlMapClientTemplate().insert("summaryAccountTemplate.editSummaryAccountTemplate", input);
					input.setTemplate(obj.get(i).get("templateValueId"));
					if(input.getTemplateEdited().equalsIgnoreCase("Y"))
					{
						System.out.println(input.getTemplateEdited()+"		: template edited");
						int counter=0;
						while(input.getTemplate().indexOf(".")>=0 && input.getSegmentId().indexOf(".")>=0)
						{	System.out.println(counter);
							counter++;
							SummaryAccountTemplateInfoBean templateDetails = new SummaryAccountTemplateInfoBean();
							templateDetails.setTemplate(input.getTemplate().substring(0, input.getTemplate().indexOf(".")));
							templateDetails.setSegmentId(input.getSegmentId().substring(0, input.getSegmentId().indexOf(".")));
							templateDetails.setFlexFieldId(input.getFlexFieldId());
							templateDetails.setUserId(input.getUserId());
							templateDetails.setTemplateId(input.getTemplateId());
	//						templateDetails.setSegmentId(segmentId);
//							System.out.println(counter+":	"+input.getSegmentId().substring(0, input.getSegmentId().indexOf("."))+"	"+input.getTemplate().substring(0, input.getTemplate().indexOf(".")));
//							System.out.println("in query details: \nFlex Field Id: "+templateDetails.getFlexFieldId()
//									+"\nTemplate Id: "+templateDetails.getFlexFieldId()+
//									"\nSegment Id: "+templateDetails.getSegmentId()+
//									"\nTemplate: "+ templateDetails.getTemplate());
							getSqlMapClientTemplate().update("summaryAccountTemplate.editSummaryAccountTemplateDetails", templateDetails);
							input.setTemplate(input.getTemplate().substring(input.getTemplate().indexOf(".")+1, input.getTemplate().length()));
							input.setSegmentId(input.getSegmentId().substring(input.getSegmentId().indexOf(".")+1, input.getSegmentId().length()));
							
						}
//						System.out.println(input.getTemplate());
						if(input.getTemplate().indexOf(".")<0 && input.getSegmentId().indexOf(".")<0)
						{
//							System.out.println(counter+1+":	"+input.getSegmentId()+"	"+input.getTemplate());
							SummaryAccountTemplateInfoBean templateDetails = new SummaryAccountTemplateInfoBean();
							templateDetails.setTemplate(input.getTemplate());
							templateDetails.setSegmentId(input.getSegmentId());
							templateDetails.setFlexFieldId(input.getFlexFieldId());
							templateDetails.setUserId(input.getUserId());
							templateDetails.setTemplateId(input.getTemplateId());
							getSqlMapClientTemplate().update("summaryAccountTemplate.editSummaryAccountTemplateDetails", templateDetails);
						}
						else
							System.out.println("error");
					}
					
					status="done";
					System.out.println("editSummaryAccountTemplate Completed");
				}
			}
		}
		catch (Exception e)
		{
			logObj.info("Exception in getting SummaryAccountTemplate  - addSummaryAccountTemplate method");
			logObj.error(e);
			System.out.println("Error in addSummaryAccountTemplate:                 \nStart\n"+e+"\nend\n");
			status=e.getClass().toString();
		}
		return status;
		
	}
	
	public List<SummaryAccountTemplateInfoBean> getSegmentsForEditRecord(String templateId)
	{
		List<SummaryAccountTemplateInfoBean> segmentsForEditRecord = null;
		try {
			segmentsForEditRecord = getSqlMapClientTemplate().queryForList("summaryAccountTemplate.getSegmentsForEditRecord",templateId);
		} catch (Exception e) {
			logObj.info("Exception in getting Segments For Edit Record  - getSegmentsForEditRecord method");
			logObj.error(e);
			System.out.println("Error in getSegmentsForEditRecord:                 \nStart\n"+e+"\nend\n");
		}
		return segmentsForEditRecord;
	}
	
	public List<SummaryAccountTemplateInfoBean> getRollUpGroups(String segmentId)
	{
		List<SummaryAccountTemplateInfoBean> rollUpGroups = null;
		try {
			rollUpGroups = getSqlMapClientTemplate().queryForList("summaryAccountTemplate.getRollUpGroups",segmentId);
		} catch (Exception e) {
			logObj.info("Exception in getting Roll Up Groups  - getRollUpGroups method");
			logObj.error(e);
			System.out.println("Error in getRollUpGroups:                 \nStart\n"+e+"\nend\n");
		}
		return rollUpGroups;
	}
}


